package com.zhuhjay.service.system.wxmp.strategy.message;

import cn.hutool.core.util.StrUtil;
import com.zhuhjay.common.redis.util.RedisUtils;
import com.zhuhjay.common.wxmp.builder.TextBuilder;
import com.zhuhjay.service.system.model.entity.SystemOauth;
import com.zhuhjay.service.system.service.SystemOauthService;
import com.zhuhjay.service.system.wxmp.strategy.AbstractMessageStrategy;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import static com.zhuhjay.common.base.constant.CacheConstant.WX_BIND_CODE_PREFIX;
import static com.zhuhjay.common.base.constant.CacheConstant.WX_UNBIND_CODE_PREFIX;
import static com.zhuhjay.service.system.enums.OauthTypeEnum.WECHAT;

/**
 * @author ZhuHJay
 * @date 2023/11/12 21:56
 */
@Lazy
@Component
@RequiredArgsConstructor
public class BindOrNotMessage extends AbstractMessageStrategy {

    private final SystemOauthService oauthService;

    @Override
    public boolean support(String content) {
        return content.startsWith("绑定") || content.startsWith("解绑");
    }

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, WxMpService wxMpService) {
        String content = wxMessage.getContent();
        boolean isBind = content.startsWith("绑定");
        String code = content.substring(2).trim();

        String key = (isBind ? WX_BIND_CODE_PREFIX : WX_UNBIND_CODE_PREFIX) + code;
        String cache = RedisUtils.getCache(key);
        if (StrUtil.isBlank(cache)) {
            return new TextBuilder().build("授权码无效", wxMessage, wxMpService);
        }

        String openid = wxMessage.getFromUser();
        if (isBind) {
            SystemOauth oauth = oauthService.lambdaQuery().eq(SystemOauth::getOpenId, openid).one();
            if (oauth != null) {
                return new TextBuilder().build("【绑定】请求错误！", wxMessage, wxMpService);
            }
            // 判断用户是否已经绑定
            int userId = Integer.parseInt(cache);
            if (oauthService.getOauthByUserId(userId, WECHAT) != null) {
                return new TextBuilder().build("系统账号已被绑定！", wxMessage, wxMpService);
            }
            // 绑定
            oauthService.createOauth(userId, WECHAT, openid);
        } else {
            if (!openid.equals(cache)) {
                return new TextBuilder().build("【解绑】请求错误！", wxMessage, wxMpService);
            }
            // 该openid是否绑定账号
            SystemOauth oauth = oauthService.lambdaQuery().eq(SystemOauth::getOpenId, openid).one();
            if (oauth == null) {
                return new TextBuilder().build("系统账号尚未绑定！", wxMessage, wxMpService);
            }
            // 解绑
            oauthService.removeById(oauth.getId());
        }
        // 流程缓存清除
        RedisUtils.setCache(key, "");
        return new TextBuilder().build(
                StrUtil.format("该微信账号已成功{}系统账号！", isBind ? "绑定" : "解绑"),
                wxMessage, wxMpService);
    }

}
